/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.task;

import cn.easyplatform.contexts.ListContext;
import cn.easyplatform.contexts.RecordContext;
import cn.easyplatform.contexts.WorkflowContext;
import cn.easyplatform.dos.LogDo;
import cn.easyplatform.engine.runtime.PageTaskSupport;
import cn.easyplatform.engine.runtime.datalist.DataListUtils;
import cn.easyplatform.engine.runtime.page.PageTask;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.messages.request.SaveRequestMessage;
import cn.easyplatform.messages.response.FieldsUpdateResponseMessage;
import cn.easyplatform.messages.response.ListOpenResultResponseMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.datalist.ListUpdatableRowVo;
import cn.easyplatform.support.scripting.BreakPoint;
import cn.easyplatform.type.Constants;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;

import java.util.HashMap;
import java.util.Map;


/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class SaveCmd extends AbstractCommand<SaveRequestMessage> {

	/**
	 * @param req
	 */
	public SaveCmd(SaveRequestMessage req) {
		super(req);
	}

	@Override
	public IResponseMessage<?> execute(CommandContext cc) {
		if (req.getActionFlag() < 0) {
			cc.setBreakPoint(null);
			return new SimpleResponseMessage();
		}
		Map<String, Object> data = req.getBody();
		boolean isCommit = req.isCommit();
		WorkflowContext ctx = cc.getWorkflowContext();
		BreakPoint bp = cc.getBreakPoint();
		PageTaskSupport ps = new PageTask();
		IResponseMessage<?> resp = null;
		if (bp == null)
			resp = ps.doNext(cc, data);
		else
			resp = ps.doNextBreakPoint(cc, bp);
		if (resp != null)
			return resp;
		if (ctx.getRecord().getParameter("850") != null) {// 从列表open
			RecordContext rc = ctx.getRecord();
			rc.setParameter("815", true);
			boolean isCreate = rc.getParameterAsString("814").equals("C");
			if (isCommit) {
				ctx.commit(cc);
				ctx.setParameter("814", "R");
			}
			// 刷新
			WorkflowContext host = cc.getWorkflowContext(ctx
					.getParameterAsString("800"));
			if (host == null)
				return MessageUtils.contextNotSupport(ctx
						.getParameterAsString("800"));
			ListContext lc = host.getList(ctx.getParameterAsString("850"));
			if (lc == null)
				return MessageUtils.dataListNotFound(ctx
						.getParameterAsString("850"));
			if (isCreate) {
				if (rc.getKeyValues() == null)
					lc.appendRecord(rc, true);
				else
					isCreate = false;
			} else if (lc.getType().equals(Constants.CATALOG)) {
				// 如果不存在就加到列表中
				RecordContext tmp = lc.getRecord(rc.getKeyValues());
				if (tmp == null)
					lc.appendRecord(rc);
			}
			// 执行
			//if (!Strings.isBlank(lc.getAfterLogic())) {
			//	cc.setWorkflowContext(host);
			//	RuntimeUtils.eval(cc, lc.getAfterLogic(), rc);
			//}
			return new ListOpenResultResponseMessage(new ListUpdatableRowVo(
					rc.getKeyValues(), DataListUtils.wrapRow(cc, lc, rc),
					isCreate, rc.getParameterAsBoolean("853")));
		} else {
			// 由<taskbox>打开的功能由主功能管理
			int om = ctx.getParameterAsInt("805");
			if (om != Constants.OPEN_EMBBED) {
				ctx.commit(cc);
				if (cc.getUser().getLogLevel() >= LogDo.LEVEL_TASK)
					RuntimeUtils.log(cc, LogDo.TYPE_TASK, "commit",
							ctx.getParameterAsString("801"));
				if (isCommit) {
					cc.removeWorkflowContext();
					return new SimpleResponseMessage();
				} else {
					ctx.resetPage(cc);
					Map<String, Object> map = new HashMap<String, Object>();
					for (String name : data.keySet())
						map.put(name, ctx.getRecord().getValue(name));
					return new FieldsUpdateResponseMessage(map);
				}
			} else {
				if (isCommit) {
					ctx.commit(cc);
					if (cc.getUser().getLogLevel() >= LogDo.LEVEL_TASK)
						RuntimeUtils.log(cc, LogDo.TYPE_TASK, "commit",
								ctx.getParameterAsString("801"));
					ctx.resetPage(cc);
				}
				Map<String, Object> map = new HashMap<String, Object>();
				for (String name : data.keySet())
					map.put(name, ctx.getRecord().getValue(name));
				return new FieldsUpdateResponseMessage(map);
			}
		}
	}

	@Override
	public String getName() {
		return "task.Save";
	}
}
